package initialize

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic/v7"
	"goods_srv/global"
	"goods_srv/model"
)

// es
func InitEs() {
	global.EsClientConn, err = elastic.NewClient(
		elastic.SetURL("http://127.0.0.1:9201"),
		elastic.SetSniff(false))
	if err != nil {
		// Handle error
		panic(err)
	}
	GoodsIndex()
}

const mapping = `
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0,
    "analysis": {
      "analyzer": {
        "ik_smart_analyzer": {
          "type": "custom",
          "tokenizer": "ik_max_word"
        },
        "ik_max_word_analyzer": {
          "type": "custom",
          "tokenizer": "ik_max_word"
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "name": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_max_word"
      }
    }
  }
}
`

// 添加索引
func GoodsIndex() {
	exists, err := global.EsClientConn.IndexExists("goods").Do(context.Background())
	if err != nil {
		// Handle error
		panic(err)
	}
	if !exists {
		// Create a new index.
		createIndex, err := global.EsClientConn.CreateIndex("goods").BodyString(mapping).Do(context.Background())
		if err != nil {
			// Handle error
			panic(err)
		}
		if !createIndex.Acknowledged {
			// Not acknowledged
		}
	}
}

// 同步数据
func EsByMysql() {
	var goods []model.Goods
	global.DB.Model("goods").Find(&goods)
	bulk := global.EsClientConn.Bulk()
	for _, v := range goods {
		global.EsClientConn.IndexExists(v.Name).Do(context.Background())
		bulk.Add()
	}
	_, err := bulk.Do(context.Background())
	if err != nil {
		return
	}
}

// 搜索
func GetGoods(termQuery *elastic.TermQuery) (int64, []model.Goods) {
	searchResult, err := global.EsClientConn.Search().
		Index("goods").     // search in index "twitter"
		Query(termQuery).   // specify the query
		Sort("user", true). // sort by "user" field, ascending
		From(0).Size(10).   // take documents 0-9
		Pretty(true).       // pretty print request and response JSON
		Highlight(elastic.NewHighlight().Field("name").Fields()).
		Do(context.Background()) // execute
	if err != nil {
		// Handle error
		panic(err)
	}
	var goods []model.Goods
	if searchResult.Hits.TotalHits.Value > 0 {
		fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)

		// Iterate through results
		for _, hit := range searchResult.Hits.Hits {
			// hit.Index contains the name of the index

			// Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
			var t model.Goods
			err := json.Unmarshal(hit.Source, &t)
			if err != nil {
				// Deserialization failed
			}
			goods = append(goods, t)
			// Work with tweet
		}
	} else {
		// No hits
		fmt.Print("Found no tweets\n")
	}
	return searchResult.Hits.TotalHits.Value, goods
}
